package com.example.chapter07_client;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.chapter07_client.util.PermissionUtil;
import com.example.chapter07_client.util.ToastUtil;

import java.io.File;

public class ProviderApkActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_provider_apk);

        findViewById(R.id.btn_install).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11及以上版本，需要检查并申请管理所有文件的权限
            Log.d("Mylog, ProviderApkActivity", "Build.VERSION.SDK_INT=" + Build.VERSION.SDK_INT);
            checkAndInstall();
        } else {
            // 如果有权限，直接安装APK，如果没有权限，申请权限
            if (PermissionUtil.checkPermission(this, PERMISSIONS, PERMISSION_REQUEST_CODE)) {
                installApk();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE && PermissionUtil.checkGrant(grantResults)) {
            installApk();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void checkAndInstall() {
        if (!Environment.isExternalStorageManager()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.fromParts("package", getPackageName(), null));
            startActivity(intent);
        } else {
            installApk();
        }
    }

    private void installApk() {
//        String apkPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/chapter06-debug.apk";
        // 使用chapter06-debug，安装提示 App not installed as package appears to be invalid
        String apkPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/app-debug.apk";
        // /storage/emulated/0/Download/chapter06-debug.apk
        // 测试apk文件，D:\Developer\Android\chapter06\build\intermediates\apk\debug\chapter06-debug.apk
        Log.d("Mylog, ProviderApkActivity", "apkPath=" + apkPath);

        File apkFile = new File(apkPath);
        if (!apkFile.exists()) {
            Log.d("Mylog, ProviderApkActivity", "apk file not exists!");
            return;
        }
        if (!apkFile.canRead()) {
            Log.d("Mylog, ProviderApkActivity", "Cannot read apk file at path: " + apkPath);
            ToastUtil.show(this, "无法读取 APK 文件，请检查权限");
            return;
        }

        PackageManager pm = getPackageManager();
        PackageInfo packageArchiveInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (packageArchiveInfo == null) {
            ToastUtil.show(this, "package is destroyed!");
            return;
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, getString(R.string.file_provider), apkFile);
            Log.d("Mylog, ProviderApkActivity", "uri=" + uri.toString());
        } else {
            uri = Uri.fromFile(apkFile);
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 设置Intent的数据类型为apk文件类型
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }
}